package MCQReaderAnsweredAnalyze;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.tree.TreeNode;

import MCQReaderInterface.MainInterface;
import MCQReaderModel.BitField;
import MCQReaderModel.CaseGroup;
import MCQReaderModel.RadioGroup;
import MCQReaderModel.TextZone;
import MCQReaderModel.Zone;

public class PrintAnalysisResult {

	private String resultFilePath;
	private FileWriter fw;
	private boolean isTheBeginning = true;
	private boolean isTheEnd = false;
	private int numQCM = 1;
	private int nbPageQCM = MainInterface.getThisIsIt().getRightFrame()
			.getPdfDisplay().getNbPage();

	public PrintAnalysisResult(String resultFilePath) {
		this.setResultFilePath(resultFilePath);
		try {
			this.fw = new FileWriter(new File(resultFilePath + ".csv"));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/*
	 * entete du fichier resultat
	 */
	private void debutResult() {
		if (isTheBeginning) {
			String str = DialogBeforeAnalyzis.entete_csv + ",,,,\n";
			try {
				fw.write(str);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		this.isTheBeginning = false;
	}

	/*
	 * fin du fichier resultat
	 */
	private void finResult() {
		if (isTheEnd) {
			try {
				fw.write(",,,,\n\"Total:\",");
				fw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		this.isTheEnd = false;
	}

	/*
	 * print root Result
	 */

	private void rootResult(TreeNode root, Graphics g, Image img) {
		int size = root.getChildCount();
		try {
			fw.write("\"QCM\",\"PAGE\",,,\n");
		} catch (IOException e) {
			e.printStackTrace();
		}
		for (int i = 0; i < size; i++) {
			int numPage = MainInterface.getThisIsIt().getRightFrame()
					.getPdfDisplay().getCurrentPageNum();
			pageResult((i == 0) ? numQCM + "," : ",", root.getChildAt(i), g, i,
					img);
			if (numPage < nbPageQCM)
				MainInterface.getThisIsIt().getRightFrame().getPdfDisplay()
						.nextPage();
		}
		numQCM++;
	}

	/*
	 * Print Page result
	 */

	private void pageResult(String str, TreeNode page, Graphics g, int numPage,
			Image img) {

		int num = numPage + 1;
		for (int i = 0; i < page.getChildCount(); i++) {
			str = (i == 0) ? (str + num + ",") : ",,";
			if (page.getChildAt(i).toString().compareTo("Radio") == 0) {
				radioResult(page.getChildAt(i), g, img);
			} else if (page.getChildAt(i).toString().compareTo("Case") == 0) {
				caseResult(page.getChildAt(i), g, img);
			} else if (page.getChildAt(i).toString().compareTo("Bar code") == 0) {
				codeBarreResult(str, page.getChildAt(i), g, img);
			} else if (page.getChildAt(i).toString().compareTo("Text area") == 0) {
				textAreaResult(page.getChildAt(i), g, img);
			}

		}

	}

	/*
	 * print codeBarre result
	 */
	private void codeBarreResult(String str, TreeNode codeBarres, Graphics g,
			Image img) {
		try {
			String s = ",\"n° de page\",\"IDENTIFIANT\",,\n";
			s += ",,\"n°\",\"code\",\n";
			fw.write(s + str);
			for (int i = 0; i < codeBarres.getChildCount(); i++) {
				int num = i + 1;
				fw.write(((i == 0) ? "" : ",,") + num + ",");
				BitField code = (BitField) codeBarres.getChildAt(i);
				Rectangle rect = code.getRectangle();
				int size = code.getSize();
				for (int j = 0; j < size; j++) {
					System.out.println("yes ");
					Rectangle newRect = new Rectangle(rect.x + j * rect.width
							/ size, rect.y, rect.width / size, rect.height);
					boolean result = AnsewredQCMAnalyse.getAnalyseur().analyze(
							newRect, img, Color.green);
					if (result)
						fw.write((j == size - 1) ? Integer.toString(1) + ",\n"
								: Integer.toString(1));
					else
						fw.write((j == size - 1) ? Integer.toString(0) + ",\n"
								: Integer.toString(0));
				}
			}
			fw.write("\n,,\"QUESTIONS\",,\n,,\"type\",\"n°\",\"résultats\"\n");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/*
	 * Print Radio result
	 */
	private void radioResult(TreeNode radios, Graphics g, Image img) {
		for (int i = 0; i < radios.getChildCount(); i++) {
			try {
				fw.write(",,\"radios\",");
			} catch (IOException e) {
				e.printStackTrace();
			}
			radioGroupResult((RadioGroup) radios.getChildAt(i), g, img);
		}
	}

	/*
	 * Print RadioGroup result
	 */
	private void radioGroupResult(RadioGroup radioGroup, Graphics g, Image img) {
		try {
			for (int i = 0; i < radioGroup.getChildCount(); i++) {
				fw.write((i == 0) ? radioGroup.getNumGroup() + "," : ",,,,");
				Rectangle rect = ((Zone) radioGroup.getChildAt(i))
						.getRectangle();
				boolean result = AnsewredQCMAnalyse.getAnalyseur().analyze(
						rect, img, Color.red);
				if (result)
					fw.write(1 + "\n");
				else
					fw.write(0 + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/*
	 * print case result
	 */

	private void caseResult(TreeNode cases, Graphics g, Image img) {
		for (int i = 0; i < cases.getChildCount(); i++) {
			try {
				fw.write(",,\"cases\",");
			} catch (IOException e) {
				e.printStackTrace();
			}
			caseGroupResult((CaseGroup) cases.getChildAt(i), g, img);
		}
	}

	/*
	 * print case result
	 */

	private void caseGroupResult(CaseGroup caseGroup, Graphics g, Image img) {
		try {
			for (int i = 0; i < caseGroup.getChildCount(); i++) {
				fw.write((i == 0) ? caseGroup.getNumGroup() + "," : ",,,,");
				Rectangle rect = ((Zone) caseGroup.getChildAt(i))
						.getRectangle();
				boolean result = AnsewredQCMAnalyse.getAnalyseur().analyze(
						rect, img, Color.blue);
				if (result)
					fw.write(1 + "\n");
				else
					fw.write(0 + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/*
	 * print text area result
	 */

	private void textAreaResult(TreeNode textAreas, Graphics g, Image img) {
		try {
			for (int i = 0; i < textAreas.getChildCount(); i++) {
				TextZone zone = (TextZone) textAreas.getChildAt(i);
				int num = zone.getNumber();
				Rectangle rect = zone.getRectangle();
				g.setColor(Color.yellow);
				String str = getTextArea(rect, num, img);
				g.fill3DRect(rect.x, rect.y, rect.width, rect.height, true);
				fw.write(",,\"zone de texte\"," + num + "," + "\"" + str
						+ "\"\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private String getTextArea(Rectangle rect, int num, Image img) {
		int numPage = MainInterface.getThisIsIt().getRightFrame()
				.getPdfDisplay().getCurrentPageNum();
		String fileName = this.resultFilePath + "/question" + num + "page"
				+ numPage + ".png";
		new File(this.resultFilePath).mkdir();

		BufferedImage textArea = ((BufferedImage) img).getSubimage(rect.x,
				rect.y, rect.width, rect.height);

		File textAreaImage = new File(fileName);
		try {
			if (ImageIO.write(textArea, "png", textAreaImage))
				return fileName;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/*
	 * print the result file
	 */
	public void printResult(TreeNode root, Graphics g, Image img) {
		debutResult();
		rootResult(root, g, img);
		finResult();
	}

	/**
	 * @param resultFilePath
	 *            the resultFilePath to set
	 */
	public void setResultFilePath(String resultFilePath) {
		this.resultFilePath = resultFilePath;
	}

	/**
	 * @return the resultFilePath
	 */
	public String getResultFilePath() {
		return resultFilePath;
	}

	/**
	 * @param isTheBeginning
	 *            the isTheBeginning to set
	 */
	public void setTheBeginning(boolean isTheBeginning) {
		this.isTheBeginning = isTheBeginning;
	}

	/**
	 * @return the isTheBeginning
	 */
	public boolean isTheBeginning() {
		return isTheBeginning;
	}

	/**
	 * @param isTheEnd
	 *            the isTheEnd to set
	 */
	public void setTheEnd(boolean isTheEnd) {
		this.isTheEnd = isTheEnd;
	}

	/**
	 * @return the isTheEnd
	 */
	public boolean isTheEnd() {
		return isTheEnd;
	}

}
